#!/usr/bin/python

__author__ = 'Sumin Byeon (suminb@gmail.com)'

import random, re
import os, sys
import Image


def getfiles(rootdir):
    pattern = re.compile(".*\.(jpg|png|bmp|tiff)", re.IGNORECASE)
    filelist = []
    for root, subdirs, files in os.walk(rootdir):
        for file in files:
            if pattern.match(file):
                filelist.append(root+"/"+file)
                
    return filelist

def average(image):
    sum = [0, 0, 0]

    for i in xrange(0, image.size[0]):
        for j in xrange(0, image.size[1]):
            pixel = image.getpixel((i, j))
            for k in range(0, 3): sum[k] += pixel[k]

    for k in range(0, 3): sum[k] = sum[k]/(image.size[0]*image.size[1])

    return sum
    
def resizeall(srcdir, dstdir, tnsize):
    if not os.path.exists(dstdir):
        os.mkdir(dstdir)
        
    filelist = getfiles(srcdir)
    for file in filelist:
        image = None
        try:
            image = Image.open(file).resize(tnsize, Image.ANTIALIAS)
            avg = average(image)
            dstfile = dstdir + "/" + "%02x%02x%02x.png" % (avg[0], avg[1], avg[2])
            print "Saving as", dstfile
            image.save(dstfile)
            del image
        except:
            print "Error: Could not process", image
            continue
    
def compile(canvassize, tnsize, filelist, output):
    canvas = Image.new("RGB", canvassize)
    
    offset = [0, 0]
    offsetx = 0
    offsety = 0
    for file in filelist:
        image = None
        try:
            image = Image.open(file).resize(tnsize, Image.ANTIALIAS)
            print "Pasting", image, "at", offset
            canvas.paste(image, (offset[0], offset[1], offset[0]+tnsize[0], offset[1]+tnsize[1]))
        except:
            print "Error: Could not process", image
            continue
        
        #del originalimage
        del image
        
        offset[0] += tnsize[0]
        if offset[0] >= canvassize[0]:
            offset[0] = 0;
            offset[1] += tnsize[1]
        if offset[1] >= canvassize[1]:
            print "Warning: Canvas is full. Terminating."
            break
    
    canvas.save(output)
    del canvas

filelist = getfiles(sys.argv[1])
#resizeall(sys.argv[1], sys.argv[2], (60, 40))

#print "Shuffling files..."
#random.shuffle(filelist)

#for file in filelist:
#    print "Processing '" + file + "'..."
#    image = None
#    try:
#        image = Image.open(file)
#    except:
#        print "Error: Could not open", file
#        continue
#        
#    print " ", image.format, image.size, image.mode
#    #print "  Average color = " + str(average(image))
#    del image
    
#print "Compiling..."
#compile((1500, 1000), (60, 40), filelist, sys.argv[2])


